<template>
    <a-modal
        v-model:visible="visible"
        width="900px"
        class="dialog-modal"
        :footer="false"
    >
        <template #title></template>
        <a-card>
            <a-row>
                <a-col :flex="1">
                    <a-form ref="formRef" :model="formData">
                        <a-row>
                            <a-col :span="8">
                                <a-form-item
                                    field="queryType"
                                    :hide-label="true"
                                >
                                    <a-radio-group
                                        v-model="formData.queryType"
                                        type="button"
                                        size="medium"
                                    >
                                        <a-radio value="newest">最新</a-radio>
                                        <a-radio value="hour">按小时</a-radio>
                                        <a-radio value="day">按天</a-radio>
                                        <a-radio value="mouth">按月</a-radio>
                                    </a-radio-group>
                                </a-form-item>
                            </a-col>
                            <a-col :span="12">
                                <a-form-item
                                    :hide-label="true"
                                    field="dateRange"
                                >
                                    <a-range-picker
                                        v-model="formData.dateRange"
                                        show-time
                                        :time-picker-props="{
                                            defaultValue: [
                                                '00:00:00',
                                                '00:00:00',
                                            ],
                                        }"
                                        style="width: 380px"
                                    />
                                </a-form-item>
                            </a-col>
                            <a-col :span="4">
                                <a-form-item
                                    :hide-label="true"
                                    field="aggregateMethod"
                                >
                                    <a-select
                                        v-model="formData.aggregateMethod"
                                        placeholder="聚合方式"
                                        :trigger-props="{
                                            autoFitPopupMinWidth: true,
                                        }"
                                    >
                                        <a-option value="max">最大值</a-option>
                                        <a-option value="min">最小值</a-option>
                                        <a-option value="avg">平均值</a-option>
                                    </a-select>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </a-col>
                <a-divider
                    role="separator"
                    direction="vertical"
                    :style="{
                        height: '42px',
                    }"
                />
                <a-space :size="6" direction="vertical">
                    <a-button type="primary" size="mini" @click="search(1)">
                        <template #icon>
                            <icon-search />
                        </template>
                        {{ $t('search') }}
                    </a-button>
                    <a-button size="mini" @click="reset">
                        <template #icon>
                            <icon-refresh />
                        </template>
                        {{ $t('reset') }}
                    </a-button>
                </a-space>
            </a-row>
            <a-divider role="separator" />
            <a-row>
                <a-col :offset="21">
                    <a-radio-group
                        v-model="formData.showStyle"
                        type="button"
                        size="mini"
                        @change="fnChangeChartOrList"
                    >
                        <a-radio value="chart">图表</a-radio>
                        <a-radio value="list">列表</a-radio>
                    </a-radio-group>
                </a-col>
            </a-row>
            <a-row style="min-height: 500px; margin-top: 10px">
                <a-col>
                    <div
                        v-show="chartTableVisible"
                        style="
                            border-top: 1px solid var(--color-neutral-3);
                            border-bottom: 1px solid var(--color-neutral-3);
                        "
                    >
                        <a-spin
                            dot
                            :loading="loading"
                            title="数据加载中"
                            style="width: 100%"
                        >
                            <div>
                                <a-empty v-show="chartDataEmpty" />
                                <div v-show="!chartDataEmpty">
                                    <Chart
                                        height="500px"
                                        :option="chartOption"
                                    ></Chart>
                                </div>
                            </div>
                        </a-spin>
                    </div>
                    <div v-show="!chartTableVisible">
                        <a-table
                            row-key="id"
                            :loading="loading"
                            :columns="deviceAlert.columns"
                            :data="deviceAlert.data"
                            :bordered="false"
                            :pagination="pagination"
                            @page-change="fnChangeListPage"
                        >
                            <template #detail="{ record }">
                                <div
                                    v-for="item in record.detail"
                                    :key="item"
                                    class="detail-number"
                                >
                                    {{ item.name }} :<span>{{
                                        item.value
                                    }}</span>
                                </div>
                            </template>
                        </a-table>
                    </div>
                </a-col>
            </a-row>
        </a-card>
    </a-modal>
</template>

<script lang="ts" setup>
    import { ref, reactive, onMounted, nextTick } from 'vue';
    import { useI18n } from 'vue-i18n';
    import useLoading from '@/hooks/loading';
    import useChartOption from '@/hooks/chartOption';
    import { getDevicePropertyHisList } from '../service';

    const { t } = useI18n();
    const xAxis = ref<string[]>([]);
    const chartsData = ref<string[]>([]);

    const visible = ref(false);
    const chartTableVisible = ref(true);
    const chartDataEmpty = ref(true);
    const { loading, setLoading } = useLoading(true);
    const formRef = ref();
    const formData = reactive({
        queryType: 'newest',
        dateRange: ['', ''],
        aggregateMethod: 'min',
        showStyle: 'chart',
        deviceId: '',
        identifier: '',
    });
    const { chartOption } = useChartOption(() => {
        return {
            tooltip: {
                trigger: 'axis',
            },
            xAxis: {
                data: xAxis.value,
            },
            dataZoom: [
                {
                    type: 'slider',
                    xAxisIndex: 0,
                    start: 0,
                    end: 100,
                },
                {
                    type: 'slider',
                    yAxisIndex: 0,
                    start: 0,
                    end: 100,
                },
                {
                    type: 'inside',
                    xAxisIndex: 0,
                    start: 0,
                    end: 100,
                },
                {
                    type: 'inside',
                    yAxisIndex: 0,
                    start: 0,
                    end: 100,
                },
            ],
            yAxis: {},
            series: [
                {
                    name: '销量',
                    type: 'line',
                    data: chartsData.value,
                },
            ],
        };
    });
    function reset() {
        formRef.value.resetFields();
    }

    const pagination = reactive({
        current: 1,
        pageSize: 10,
        total: 0,
    });
    const deviceAlert = reactive({
        loading: false,
        columns: [
            {
                title: '时间',
                dataIndex: 'occurredTime',
            },
            {
                title: '数值',
                dataIndex: 'value',
            },
        ],
        data: [],
    });

    const fetchChartData = async () => {
        setLoading(true);
        const params = {
            current: 1,
            deviceId: formData.deviceId,
            identifier: formData.identifier,
            startTime: formData.dateRange[0],
            endTime: formData.dateRange[1],
            queryType: formData.queryType,
            showStyle: formData.showStyle,
        };
        try {
            const data = await getDevicePropertyHisList(params);
            const { result } = data as any;

            xAxis.value.length = 0;
            chartsData.value.length = 0;
            result.records.forEach(
                (aa: { occurredTime: string; value: string }) => {
                    xAxis.value.push(aa.occurredTime);
                    chartsData.value.push(aa.value);
                }
            );
            chartDataEmpty.value = chartsData.value.length === 0;
        } catch (err) {
            // you can report use errorHandler or other
        } finally {
            setLoading(false);
        }
    };
    const fetchListData = async (params: any) => {
        setLoading(true);
        try {
            const data = await getDevicePropertyHisList(params);
            const { result } = data as any;
            deviceAlert.data = result.records;
            pagination.total = result.total;
        } finally {
            setLoading(false);
        }
    };
    const fnChangeListPage = (pageNum: number) => {
        pagination.current = pageNum;

        fetchListData({
            size: pagination.pageSize,
            current: pageNum,
            deviceId: formData.deviceId,
            identifier: formData.identifier,
            startTime: formData.dateRange[0],
            endTime: formData.dateRange[1],
            queryType: formData.queryType,
            showStyle: formData.showStyle,
        });
    };
    function search(pageNum: number) {
        if (formData.showStyle === 'chart') {
            fetchChartData();
        } else {
            fnChangeListPage(pageNum);
        }
    }

    function open(data: any) {
        Object.assign(formData, data);
        // console.log(JSON.stringify(formData));
        reset();
        formData.showStyle = 'chart';
        visible.value = true;
        chartTableVisible.value = true;
        fetchChartData();
    }
    const fnChangeChartOrList = (value: any) => {
        if (value === 'chart') {
            chartTableVisible.value = true;
            fetchChartData();
        } else {
            chartTableVisible.value = false;
            fnChangeListPage(1);
        }
    };
    onMounted(async () => {
        nextTick(() => {
            // chartsView();
        });
    });
    defineExpose({
        open,
    });
</script>

<style lang="less" setup>
    .dialog-modal {
        .arco-modal-body {
            padding: 0 !important;
        }
    }

    .attendance-data {
        width: 800px;
        //height: ~'calc(100% - 100px)';
        height: 400px;
    }
</style>
@/hooks/chartOption
